<template>
  <div class="book-detail">
    <t-card :bordered="false" class="content-card">
      <template #title>
        <t-space size="18px">
          <div>
            <t-space size="18px">
              <h2 class="card-title">{{ warehouseName }}</h2>
              <t-dropdown :min-column-width="80" placement="bottom" trigger="click">
                <template #dropdown>
                  <t-dropdown-menu>
                    <t-dropdown-item v-for="(item, index) in warehouseList" :key="index" @click="changeWarehouse(item)">
                      <p>{{ item.name }}</p>
                    </t-dropdown-item>
                  </t-dropdown-menu>
                </template>
                <icon-font name="chevron-down-circle" />
              </t-dropdown>
            </t-space>
            <div style="display: flex;align-items: center;gap: 16px">
              <!--<p class="card-sub-title">库存数：{{ info.product_count }}</p>-->
              <!--<p class="card-sub-title">订单数：{{ info.order_count ? info.order_count : 0 }}</p>-->
              <p class="card-sub-title">库存数：<t-link theme="primary" hover="color" @click="goWarehouseProduct()">{{ info.product_count }}</t-link></p>
              <p class="card-sub-title">入库记录：<t-link theme="primary" hover="color" @click="handleOption(0)">123</t-link></p>
              <p class="card-sub-title">出库记录：<t-link theme="primary" hover="color" @click="handleOption(1)">456</t-link></p>
              <p class="card-sub-title">调拨记录：<t-link theme="primary" hover="color" @click="handleOption(2)">789</t-link></p>
            </div>
          </div>

          <!-- <t-link class="edit-btn-color" hover="color">编辑</t-link> -->
        </t-space>
      </template>
      <template #actions>
        <t-space size="8px">
          <t-button @click="handleWarehousing" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>入库
            </p>
          </t-button>
          <t-button @click="handleOutbound" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-outbound" style="font-size: 24px;margin-right: 4px"></i>出库
            </p>
          </t-button>
          <t-button @click="handleAllocation" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>调拨
            </p>
          </t-button>
          <t-button @click="handleInventory" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>盘点
            </p>
          </t-button>
        </t-space>
      </template>

      <div class="filter ">
        <t-space size="12px">
          <!--<t-cascader style="width: 160px;" v-model="params.product_classify_id" :options="classifyList" clearable @change="getData" placeholder="按产品分类">-->
          <!--  <template #label>-->
          <!--    <icon-font name="layers" style="color: #000;"/>-->
          <!--  </template>-->
          <!--</t-cascader>-->
          <t-input style="width: 220px;" v-model="params.key" clearable @change="getData" placeholder="搜索：产品名称">
            <template #label>
              <icon-font name="search" size="16px" style="color:#000;font-weight: bold"/>
            </template>
          </t-input>
        </t-space>
      </div>

      <div class="pt16">
        <t-table
          rowKey="id"
          :data="lists"
          :columns="columns"
          :stripe="stripe"
          :bordered="bordered"
          :hover="hover"
          :size="size"
          :max-height="maxHeight"
          :table-layout="tableLayout ? 'auto' : 'fixed'"
          :showHeader="showHeader"
          cellEmptyContent="-"
          resizable
          :loading="loading"
          @page-change="pageChange"
          :pagination="pagination"
          :selected-row-keys="selectedRowKeys"
          @select-change="handleSelectChange"
        >
          <template #title-slot-option></template>
          <template #product_thumb="{row}">
            <t-image-viewer v-if="row.product_thumb" :images="[row.product_thumb]" :closeOnEscKeydown="false">
              <template #trigger="{ open }">
                <div class="tdesign-demo-image-viewer__ui-image" @click="open">
                  <p class="prod-img">
                    <img alt="test" :src="row.product_thumb"/>
                  </p>
                  <div class="tdesign-demo-image-viewer__ui-image--hover">
                    <span><browse-icon size="1.4em"/> </span>
                  </div>
                </div>
              </template>
            </t-image-viewer>
            <p v-else>-</p>
          </template>
          <template #product_title="{row}">
            <div class="">
              <p class="item-title">{{row.product_title}}</p>
              <p v-if="row.sn" class="item-sn">S/N:{{ row.sn }}</p>
            </div>
          </template>
          <template #unit_price="{row}">
            <div class="flex align-center">
              <p>{{row.unit_price ? `￥${row.unit_price}` : '-'}}</p>
            </div>
          </template>
          <template #sell_price="{row}">
            <div class="flex align-center">
              <p>{{row.sell_price ? `￥${row.sell_price}` : '-'}}</p>
              <t-tooltip v-if="!row.sell_price" content="请到产品库设置产品的售价">
                <icon-font name="help-circle" style="margin-left: 6px"></icon-font>
              </t-tooltip>
            </div>
          </template>
          <template #option="{row}">
            <t-space size="12px">
              <t-popconfirm theme="danger" placement="top-right" :visible="visible && editId === row.id" :confirm-btn="{
                size: 'medium',
                content: '确定'
              }" :cancel-btn="{
                size: 'medium',
                content: '取消'
              }" @confirm="handleEdit($event, row)" @visible-change="onVisibleChange">
                <template #icon><p></p></template>
                <template #content>
                  <div style="width: 400px">
                    <h3 class="popconfirm-title">编辑</h3>
                    <div class="pt16">
                      <t-form :data="formData" :rules="rules" ref="form" label-align="top" @submit="onSubmit($event, row)">
                        <t-form-item label="备注" name="remark">
                          <t-textarea v-model="formData.remark" placeholder="输入备注"></t-textarea>
                        </t-form-item>
                        <t-form-item label="排序（大至小）" name="sort">
                          <t-input-number v-model="formData.sort" style="width: 200px" :min="0" placeholder="输入排序"></t-input-number>
                        </t-form-item>
                      </t-form>
                    </div>
                  </div>
                </template>
                <!--<t-link theme="primary" class="edit-btn-color" hover="color" @click="clickEdit(row)">编辑</t-link>-->
              </t-popconfirm>
              <t-link v-if="row.quantity > 0" theme="primary" class="edit-btn-color" hover="color" @click="onOutbound(row)">出库</t-link>
              <t-link theme="primary" class="edit-btn-color" hover="color" @click="handleInfo(row)">详情</t-link>
              <t-popconfirm theme="danger" placement="top-right" confirm-btn="删除" @confirm="handleDelete($event, row)">
                <template #content>
                  <div>
                    <h3 class="popconfirm-title">确认删除？</h3>
                    <p>删除后数据将不可恢复！是否确认删除？</p>
                  </div>
                </template>
                <t-link theme="danger" variant="outline" hover="color">删除</t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </t-table>

      </div>
    </t-card>

    <!-- 产品入库 -->
    <product-warehousing ref="warehousing" :warehouse_id="params.warehouse_id" @refresh="getList"></product-warehousing>
    <!-- 产品出库 -->
    <product-outbound ref="outbound" :warehouse_id="params.warehouse_id" @refresh="getList"></product-outbound>
    <!-- 产品调拨 -->
    <product-allot ref="allot" :warehouse_id="params.warehouse_id"></product-allot>
    <!-- 产品盘点 -->
    <product-inventory ref="inventory" :warehouse_id="params.warehouse_id"></product-inventory>


    <!-- 出库 -->
    <com-outbound ref="ComOutbound" @confirm="confirmOutbound"></com-outbound>
    <!--<product-add ref="add" :warehouseId="warehouseId" @refresh="getData"></product-add>-->

    <!-- 详情 -->
    <order-info ref="info"></order-info>
  </div>
</template>

<script lang="jsx">
import { Input, Textarea } from 'tdesign-vue';
import {IconFont, CalendarIcon, BrowseIcon} from "tdesign-icons-vue";
import IconUAV from "@/components/icon-UAV/index.vue";
import ProductAdd from "@/pages/warehouse/product/add/index.vue";
import {
  warehouse_product_stockDeleteApi,
  warehouse_product_stockEditApi,
  warehouse_product_stockListApi
} from "@/api/warehouseInventory";
import OrderInfo from "@/pages/warehouse/product/components/order-info.vue";
import {warehouseDetailApi, warehouseListApi} from "@/api/warehouse";
import {productListApi} from "@/api/product";
import {classifyListApi} from "@/api/classify";
import ProductWarehousing from "@/pages/warehouse/components/product-warehousing/product-warehousing.vue";
import ProductOutbound from "@/pages/warehouse/components/product-outbound/product-outbound.vue";
import ProductAllot from "@/pages/warehouse/components/product-allot/product-allot.vue";
import ProductInventory from "@/pages/warehouse/components/product-inventory/product-inventory.vue";

import ComOutbound from "@/pages/warehouse/components/product-outbound/config-info.vue";
import {warehouse_orderCreateApi} from "@/api/InOutStorage";

export default {
  name: 'Warehousing',
  components: {ComOutbound, ProductWarehousing, ProductOutbound, ProductAllot, ProductInventory, OrderInfo, IconUAV, IconFont, BrowseIcon, ProductAdd},
  data() {
    return {
      renderPrefixIcon: () => <CalendarIcon/>,
      params: {
        page: 1,  // 当前页
        limit: 10,  // 每页条数
        warehouse_id: '', // 仓库ID
        product_id: '', // 产品ID
        product_classify_id: '', // 产品分类ID
        key: '',  // 关键字
        status: '', // 状态
      },

      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        //{colKey: 'row-select', type: 'multiple', width: 40,},
        {colKey: 'id', title: 'ID', align: 'center', width: 60,},
        {colKey: 'product_thumb', title: '图片', align: 'center', width: 80,},
        {colKey: 'product_title', title: '产品', width: 240, ellipsis: true},
        //{colKey: 'sn', title: 'SN', width: 220},
        {colKey: 'unit_title', title: '单位', align: 'center', width: 90},
        {colKey: 'quantity', title: '库存', align: 'center', width: 100},
        {colKey: 'unit_price', title: '入库价', width: 140},
        {colKey: 'sell_price', title: '售价', width: 140},
        //{colKey: 'sort', title: '排序', width: 80},
        //{colKey: 'order_date', title: '最近订单日期', width: 140},
        //{colKey: 'unit_price', title: '最近含税单价', width: 140},
        {colKey: 'remark', title: '备注', ellipsis: true, width: 180,
          edit: {
            component: Textarea,
            props: {
              clearable: true,
              autofocus: true,
              maxLength: 140,
            },
            // 透传给 component: Input 的事件
            on: (editContext) => ({
              onBlur: () => {
                this.handleEdit(editContext)
              },
            }),
          }
        },
        {colKey: 'option', title: 'title-slot-option', fixed: 'right', width: 160},
      ],
      selectedRowKeys: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
      },
      maxHeight: 472,
      loading: false,
      productList: [],
      classifyList: [],

      statusOptions: [
        //(1 回收站, 0 正常)
        { label: '正常', value: 0 },
        { label: '回收站', value: 1 },
      ],

      editId: '',
      visible: false,
      formData: {
        remark: '', // 备注
        sort: '', // 排序
      },
      rules: {
        //remark: [{ required: true, message: '请输入备注', trigger: 'blur' },],
        //sort: [{ required: true, message: '请输入排序', trigger: 'blur' },],
      },

      warehouseList: [],
      warehouseName: '',
      warehouseId: '',
      info: {}
    };
  },
  mounted() {
    let height = document.documentElement.clientHeight - 244;
    this.maxHeight = height
    window.onresize = () => {
      // 获取屏幕高度 - 顶部高度
      height = document.documentElement.clientHeight - 244;
      this.maxHeight = height
    };

    const { warehouseId } = this.$route.query
    this.warehouseId = Number(warehouseId)
    this.params.warehouse_id = Number(warehouseId)

    this.getData()
    this.getWarehouseInfo()
    this.getWarehouseList()
    this.getProductList()
    this.getClassifyList()
  },
  methods: {
    handleEdit(context) {
      console.log('context', context)
      const params = {
        id: context.editedRow.id,
        sort: context.editedRow.sort, // 排序
        remark: context.editedRow.remark.target.value
      }
      warehouse_product_stockEditApi(context.editedRow.id, params).then(res => {
        this.$message.success('编辑成功')
        this.getList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    goWarehouseProduct() {
      this.$router.push({
        name: 'WarehouseProduct',
        query: {
          warehouseId: this.warehouseId
        }
      })
    },
    // 点击操作项
    handleOption(orderType, item) {
      this.$router.push({
        name: 'WarehouseOrderList',
        query: {
          orderType,
          warehouseId: this.warehouseId
        }
      })
    },
    // 获取仓库信息
    getWarehouseInfo() {
      warehouseDetailApi(this.warehouseId).then(res=> {
        this.info = res.data
      }).catch(err=> {
        console.log('err', err)
      })
    },
    // 切换仓库
    changeWarehouse(item) {
      this.warehouseName = item.name
      this.warehouseId = item.id
      this.params.warehouse_id = item.id

      this.$router.replace({
        path: this.$route.path,
        query: { warehouseId: item.id }
      });
      this.getWarehouseInfo()
      this.getData()
    },
    // 获取列表
    getClassifyList() {
      const params = {
        page: 1,
        limit: 9999,
        belong_module: 'product_classify',
      }
      classifyListApi(params).then(res=> {
        //this.classifyList = res.data.map(item=> ({ label: item.title, value: item.id }))
        const lists = res.data.map(item=> ({ label: item.title, value: item.id, id: item.id, pid: item.pid }))
        const hierarchy = this.buildHierarchyRecursive(lists)
        //hierarchy.unshift({label: '顶级分类', value: 0, id: 0, pid: 0})
        this.classifyList = hierarchy
      })
    },
    buildHierarchyRecursive(data, pid = 0) {
      return data
        .filter(item => item.pid === pid)
        .map(item => ({
          ...item,
          children: this.buildHierarchyRecursive(data, item.id)
        }));
    },
    // 获取产品列表
    getProductList() {
      const params = {
        page: 1,
        limit: 9999
      }
      productListApi(params).then(res => {
        this.productList = res.data.map(item=> ({ label: item.title, value: item.id }))
      })
    },
    // 获取仓库列表
    getWarehouseList() {
      const params = {
        page: 1,
        limit: 9999
      }
      warehouseListApi(params).then(res => {
        this.warehouseList = res.data.map(item=> ({ ...item, label: item.name, value: item.id }))
        let data = this.warehouseList.find(item => item.id === this.warehouseId)
        this.warehouseName = data.name
      })
    },
    // 入库
    handleWarehousing() {
      this.$refs.warehousing.open(0)
    },
    // 出库
    handleOutbound() {
      this.$refs.outbound.open(1)
    },
    // 调拨
    handleAllocation() {
      this.$refs.allot.open(2)
    },
    // 盘点
    handleInventory() {
      this.$refs.inventory.open(3)
    },
    onVisibleChange(val, context = {}) {
      // trigger 表示触发来源，可以根据触发来源自由控制 visible
      if (context && context.trigger !== 'confirm') {
        this.visible = val;
      }
    },
    onSubmit({ validateResult, firstError }, row) {
      if (validateResult === true) {
        this.editId = ''
        this.visible = false
        warehouse_product_stockEditApi(row.id, this.formData).then(res => {
          this.$message.success('编辑成功')
          this.getList()
        }).catch(err => {
          console.log('err', err)
        })
      } else {
        this.$message.warning(firstError);
      }
    },
    // 添加
    goProductAdd() {
      this.$refs.add.open('add');
    },
    // 编辑
    //handleEdit(row) {
    //  this.$refs.form.submit()
    //},
    clickEdit(row) {
      this.editId = row.id
      this.formData = {
        remark: row.remark,
        sort: row.sort,
      }
    },
    handleInfo(row) {
      //this.$refs.info.open(row.id)
      this.$router.push({
        name: 'WarehouseProductInfo',
        query: {
          id: row.id,
          sn:row.sn,
          unit_id: row.unit_id
        }
      })
    },
    // 出库
    onOutbound(row) {
      this.$refs.ComOutbound.open('first', row)
    },
    // 确认出库
    confirmOutbound(row) {
      const params = {
        order_type: 1, // 必需 订单类型（0入库；1出库；2调拨；3盘点）
        warehouse_id: this.warehouseId, // 必需 出/入仓库ID（调拨时：调入仓库ID）
        next_warehouse_id: '', // 可选 调出仓库ID（调拨时需要填写）
        order_date: this.$dayjs().format('YYYY-MM-DD'), // 必需 订单日期（yyyy-MM-dd）
        order_no: '', // 可选  单号（空值时系统生成）
        discount_amount: '', // 可选 总优惠金额（两位小数）
        linkman: '', // 联系人 可选
        phone: '', // 联系电话 可选
        operator_name: '', // 经办人 可选
        batch_no: '', // 批次编号 可选
        product_data: [{
          product_id: row.product_id, // 产品ID
          unit_id: row.unit_id,  // 单位ID
          quantity: row.quantity, // 数量两位小数
          is_sn: row.is_sn, // 开启SN序列号（0关闭；1开启）
          sn: row.sn, // SN数据
          unit_price: row.unit_price, // 含税单价（进货价）
          remark: row.remark, // 备注（50个字内）
        }], // 可选产品清单(JSON数据）
        remark: '', // 备注
      }
      params.product_data = JSON.stringify(params.product_data)
      warehouse_orderCreateApi(params).then(res=> {
        this.$message.success(`出库成功`)
        this.getList()
      }).catch(err=> {
        console.log(err)
      })
    },
    // 复制
    //handleCopy(row) {
    //  this.$refs.add.open('copy', row)
    //},
    // 删除
    handleDelete(evt, row) {
      warehouse_product_stockDeleteApi({id: row.id}).then(res => {
        this.$message.success('删除成功')
        this.getList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 获取数据
    getData() {
      this.pagination.defaultCurrent = 1
      this.getList()
    },
    // 获取列表
    getList() {
      this.loading = true
      this.params.page = this.pagination.defaultCurrent
      warehouse_product_stockListApi(this.params).then(res => {
        this.pagination.total = res.count
        this.lists = res.data.map(item=> ({...item, visible: false}))
      }).catch(err => {
      }).finally(() => {
        this.loading = false
      })
    },
    // 切换分页
    pageChange(pageInfo) {
      const {current, defaultCurrent, defaultPageSize,} = pageInfo
      this.pagination.defaultCurrent = current
      this.getList()
    },
    handleSelectChange(value, {selectedRowData}) {
      this.selectedRowKeys = value;
    },
  },
}
</script>

<style lang="less" scoped>
.book-detail {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: var(--td-radius-medium);
  background-color: #FFFFFF;
}

.item-title {
  font-weight: 500;
}

.item-sn {
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  text-align: left;
  color: rgba(0,0,0,0.6);
}

/deep/ .content-card {

  .t-card__header {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);
    padding-bottom: 0;
  }

  .t-card__body {
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl) var(--td-comp-paddingTB-m);
  }

  .card-sub-title {
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    text-align: left;
    color: #000000;
    padding-top: 8px;
  }

  .setting-btn {
    font-size: 14px;
    font-weight: 400;
    line-height: 19.6px;
    text-align: left;
    color: #005687;
  }

  .invite-btn {
    font-size: 12px;
    font-weight: 400;
    line-height: 16.8px;
    text-align: left;
    color: #005687;

    background-color: #F3FBFF;
    border: 1px solid #005687;
    border-radius: var(--td-radius-default);
  }
}

/deep/ .action-btn {
  width: 126px;
  height: 42px;
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  text-align: left;
  color: #FFFFFF;

  .t-button__text {
    display: flex;
    align-items: center;
    justify-content: center;

    i {
      z-index: 2;
      font-size: 12px;
      font-weight: bold;
      margin-right: 6px;

      &:after {
        position: absolute;
        display: inline-block;
        content: '';
        top: 50%;
        left: 50%;
        width: 14px;
        height: 14px;
        z-index: -1;
        background-color: #FFFFFF;
        border-radius: var(--td-radius-round);
        transform: translateX(-50%) translateY(-50%);
      }
    }
  }
}

.action-btn1 {
  background-color: #14A54E;
  border: 1px solid #14A54E;

  i {
    color: #14A54E;
  }
}

.action-btn2 {
  background-color: #FF5C46;
  border: 1px solid #DFE3E7;
}

.action-btn3 {
  background-color: #565656;
  border: 1px solid #DFE3E7;
}

.action-btn4 {
  color: black;
  background-color: #F9F9F9;
  border: 1px solid #E1E1E1;
}

/deep/ .filter {
  padding-top: 13px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .t-input, .t-input.t-is-readonly {
    //background-color: #F8F8F8;
  }
}

//.import-btn {
//  width: 69px;
//  color: #000000;
//  font-size: 14px;
//  font-weight: 400;
//  line-height: 19.6px;
//  background-color: #F9F9F9;
//  border: 1px solid #E1E1E1;
//}

.income {
  color: #14A54E;
  display: flex;
  align-items: center;

  i {
    width: 17px;
    height: 17px;
    color: #FFFFFF;
    font-size: 12px;
    display: flex;
    margin-left: 8px;
    align-items: center;
    justify-content: center;
    background-color: #14A54E;
    border-radius: var(--td-radius-small);
  }
}

.expenditure {
  color: #FF5C46;
  display: flex;
  align-items: center;

  i {
    width: 17px;
    height: 17px;
    color: #FFFFFF;
    font-size: 12px;
    display: flex;
    margin-left: 8px;
    align-items: center;
    justify-content: center;
    background-color: #FF5C46;
    border-radius: var(--td-radius-small);
  }
}

.footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #F9F9F9;
  padding: var(--td-comp-paddingTB-m) var(--td-comp-paddingLR-xl);
  padding-right: var(--td-comp-paddingLR-xxl);
}
</style>
